/**
 * 
 */
package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.AnyRes;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.FileProvider;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.jdy.haoduoai.FileUtils;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.ChatWallPaperAapter;
import com.jdy.haoduoai.adapter.SpeakForYouItem;
import com.jdy.haoduoai.adapter.SpeakWordHistoryAdapter;
import com.jdy.haoduoai.adapter.VoicePlayClickListener;
import com.jdy.haoduoai.enums.MediaType;
import com.jdy.haoduoai.enums.PlayState;
import com.jdy.haoduoai.enums.PosterType;
import com.jdy.haoduoai.enums.SendState;
import com.jdy.haoduoai.enums.SpeakForYouType;
import com.jdy.haoduoai.event.OnMediaResendEvent;
import com.jdy.haoduoai.event.OnTextSelectEvent;
import com.jdy.haoduoai.fragment.GridViewFragment;
import com.jdy.haoduoai.fragment.TagsFragment;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.intface.OnRecommendItemClickListener;
import com.jdy.haoduoai.intface.PhotoSourceDelegate;
import com.jdy.haoduoai.model.AlbumCollectionItem;
import com.jdy.haoduoai.model.AlbumItem;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.SpeakFouYouRecordItem;
import com.jdy.haoduoai.model.TipWordCategoryItem;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.socket.DeviceStateListener;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.DateUtils;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.LePreference;
import com.jdy.haoduoai.util.LeXiaoXiaoBanLog;
import com.jdy.haoduoai.util.OnDataReceivedListener;
import com.jdy.haoduoai.util.PathUtil;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.tencent.android.tpush.XGPushClickedResult;
import com.tencent.android.tpush.XGPushManager;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.droidparts.widget.ClearableEditText;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

//import com.jdy.haoduoai.R;

@SuppressLint("InlinedApi")
public class SpeakForYouActivity extends BaseActivity implements
    OnClickListener, OnDataReceivedListener, OnRefreshListener, DeviceStateListener {

  private static final String TAG = SpeakForYouActivity.class.getSimpleName();

  @InjectView(id = R.id.text_category_layout)
  private LinearLayout mHLayout;
  @InjectView(id = R.id.text_selection_viewpager)
  private android.support.v4.view.ViewPager mTagsViewPager;
  @InjectView(id = R.id.radiogroup)
  private RadioGroup mViewPagerIndicators;
  @InjectView(id = R.id.radio_img, click = true)
  private ImageView mRadioImg;
  @InjectView(id = R.id.ime_img, click = true)
  private ImageView mImeImg;
  @InjectView(id = R.id.chat_bg_img, click = true)
  private ImageView mChatBgImg;
  @InjectView(id = R.id.bottom_hs)
  private HorizontalScrollView bottomHS;
  @InjectView(id = R.id.recommend_pager)
  private android.support.v4.view.ViewPager mRecommendVp;
  @InjectView(id = R.id.recommend_indicator_rg)
  private RadioGroup mCircleRg;
  @InjectView(id = R.id.txt_to_send_edittext)
  private ClearableEditText mTxt2SendEtx;
  @InjectView(id = R.id.center_layout)
  private RelativeLayout mCenterLayout;
  @InjectView(id = R.id.img_closevideo, click = true)
  private ImageView img_closevideo;
  @InjectView(id = R.id.live_video_layout)
  private View live_video_layout;
  @InjectView(id = R.id.ask_layout)
  private View ask_layout;
  @InjectView(id = R.id.speak_root_layout)
  private RelativeLayout mRootLayout;
  @InjectView(id = R.id.input_selection_layout)
  private RelativeLayout mInputSelectionLayout;
  @InjectView(id = R.id.ask_search_tv, click = true)
  private TextView mAskSearchTv;
  @InjectView(id = R.id.history_record_listview)
  private ListView mHistoryLV;
  @InjectView(id = R.id.refresh_layout)
  private SwipeRefreshLayout mSwipeRefreshLayout;
  @InjectView(id = R.id.change_bg_img)
  private ImageView mChangeBgImg;
  @InjectView(id = R.id.connection_state_tv)
  private TextView mConnectionStateTv;
  @InjectView(id = R.id.tv_reconnect)
  private TextView tv_reconnect;
  @InjectView(id = R.id.bg_select_gv)
  private GridView mBgSelectGv;

  private LeUser mLeUser;
  private LayoutInflater mInflater;
  private List<Integer> rbIds;
  private List<Integer> recommend_rbIds;
  private List<SpeakForYouItem> historyWordList;
  private SpeakWordHistoryAdapter sha;
  private int selectedTextViewId = -1;
  private ColorStateList oldColors;
  private List<TextView> categoryTextViewList;

  private int mLastPage = 1;
  private List<TipWordCategoryItem> tipWordList;
  private SparseArray<List<TipWordCategoryItem>> tipWordListSpArray = new SparseArray<List<TipWordCategoryItem>>();
  int tipIndex = 0;

  private enum ResourceType {
    None, Text, Video, Background,
  }

  private Uri mResultURI;

  private String mAvatarPath;

  private static final int PHOTO_PICKED_WITH_DATA = 1001;// 相册
  private static final int CAMERA_WITH_DATA = 1002;// 相机
  private static final int CROP_PHOTO = 101;
  private static final File PHOTO_DIR = new File(
      Environment.getExternalStorageDirectory() + "/CameraCache");
  private File mCurrentPhotoFile;// 照相机拍照得到的图片
  private File mCacheFile;
  private static String fileName;
  private RecommendPagerAdapter mRecommendPagerAdapter;
  private String mChatBgPath;
  private int mListViewColor;

  private boolean mBackPressed;

  private enum ConnectState {
    NONE, CONNECTTING, ERROR, TIMEOUT,
  }
  private void bindService() {
    SocketThreadManager.getInstance().requestDeviceDetails();
  }

  @Override
  public void onBackPressed() {
    mBackPressed = true;
    super.onBackPressed();
  }

  @Override
  protected void onStop() {
    super.onStop();
  }

  private boolean videoLoad;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.speak_for_u);
    setTitle("替你发声");


    XGPushClickedResult result = XGPushManager.onActivityStarted(this);
    if (result != null) { // 如果result为null就说明通知不是来自Xinge
      String customContent = result.getCustomContent();
      String more = "";
      // 解析自定义key-value
      if (customContent != null && customContent.length() != 0) {
        // customContent 是服务端传过来的key-value值，在这里根据需求解析处理
//        Log.e(TAG, customContent);
//        mFromXG = true;
        finish();
      }
    }

      mBackImageButton.setOnClickListener(new OnClickListener() {
          @Override
          public void onClick(View v) {
             mBackPressed= true;
             finish();
          }
      });

    if (device_view != null) {
      device_view.setVisibility(View.VISIBLE);
      device_view.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
          startActivity(new Intent(SpeakForYouActivity.this,
              DevicePropertyActivity.class));
        }
      });
    }

    mAvatarPath = PathUtil.getSpeakForYouWallpaperPath(getApplicationContext());
    init();
    bindService();
    EventBus.getDefault().register(this);
    checkUserImSig();
    buildCircles();
    mCircleRg.check(recommend_rbIds.get(0));
  }

  @Override
  protected void onResume() {
    super.onResume();

    mListViewColor = LePreference.getInstance().getInt(
        "speak_for_you_listview_bg_color", Color.parseColor("#f1f1f1"));

    mChatBgPath = LePreference.getInstance().getString(
        "speak_for_you_wallpaper");

    Uri tmpUri = null;

    if (Tools.isNotEmpty(mChatBgPath))
      tmpUri = Uri.parse(mChatBgPath);

    if (!LeConfig.isDeviceConnect || !LeConfig.isInternetAvailable) {
      if (device_view != null) {
        device_view.setPlaying(false);
      }
    }

    try {
      JSONObject jsonObject = new JSONObject();
      jsonObject.put("code", 202);
      jsonObject.put("act", "videostatu");
      SocketThreadManager.getInstance().send(jsonObject.toString());
    } catch (JSONException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }

    setChatBgWallpaper(mListViewColor, tmpUri);
  }

  @Override
  protected void onPause() {
    super.onPause();

    LePreference.getInstance().save("speak_for_you_listview_bg_color",
        mListViewColor);
    LePreference.getInstance().save("speak_for_you_wallpaper", mChatBgPath);

    if (VoicePlayClickListener.currentPlayListener != null)
      VoicePlayClickListener.currentPlayListener.stopPlayVoice();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);

    SocketThreadManager.getInstance().removeDataReceivedListener(this);
    SocketThreadManager.getInstance().removeDeviceStateListener(this);
  }

  @Subscribe
  public void onEvent(OnTextSelectEvent event) {
    String msg = event.getContent();
    if (Tools.isNotEmpty(msg)) {
      mTxt2SendEtx.setText(mTxt2SendEtx.getText().toString().trim() + msg);
      mTxt2SendEtx.setSelection(mTxt2SendEtx.getText().length());
      mTxt2SendEtx.requestFocus();
      showSoftKeyboard();
      mTxt2SendEtx.setCursorVisible(true);
      foldLayout();
    }
  }

  @Subscribe
  public void onEvent(OnMediaResendEvent event) {
    SpeakForYouItem sfyi = event.getSfyi();
    switch (sfyi.SFYType) {
    case TEXT:
      speak(sfyi.Caption, sfyi);
      break;
    case VIDEO:
      playvideo(sfyi.episode_id, "cartoon", sfyi);
      break;
    case VOICE:
      break;
    default:
      break;
    }
  }

  private void init() {
    mSwipeRefreshLayout.setOnRefreshListener(this);
    mSwipeRefreshLayout.setColorScheme(R.color.refresh_progress_1,
        R.color.refresh_progress_2, R.color.refresh_progress_3,
        R.color.refresh_progress_4);

    mLeUser = ((LeXiaoXiaoBanApp) this.getApplication()).getUser();
    historyWordList = new ArrayList<SpeakForYouItem>();
    getHistoryRecords();
    this.mInflater = LayoutInflater.from(this);
    loadTipWordCategory();

    mTagsViewPager.setOnPageChangeListener(new OnPageChangeListener() {
      @Override
      public void onPageSelected(int arg0) {
        mViewPagerIndicators.check(rbIds.get(arg0));
      }

      @Override
      public void onPageScrolled(int arg0, float arg1, int arg2) {
      }

      @Override
      public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub
      }
    });

    loadRecommendationData();

    mTxt2SendEtx.setHorizontallyScrolling(false);
    mTxt2SendEtx.setMinLines(2);
    mTxt2SendEtx.setMaxLines(4);
    mTxt2SendEtx
        .setOnEditorActionListener(new OnEditorActionListener() {
          @Override
          public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == 6) {
              return true;
            } else
              return false;
          }
        });

    mTxt2SendEtx.setOnFocusChangeListener(new OnFocusChangeListener() {

      @Override
      public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
          mTxt2SendEtx.setHint(getResources().getString(
              R.string.text_input_prompt));
          mTxt2SendEtx.setCursorVisible(true);
          foldLayout();
          if (mTxt2SendEtx.getTag() == null || (boolean) mTxt2SendEtx.getTag()) {
            showSoftKeyboard();
            mTxt2SendEtx.setTag(true);
          }

          if (Tools.isEmpty(mTxt2SendEtx.getText().toString().trim())) {
            LeMachine lb = LeXiaoXiaoBanApp.getInstance().getBaby();
            mTxt2SendEtx.setText(lb.name + "，");
            mTxt2SendEtx.setSelection(mTxt2SendEtx.getText().length());
            mTxt2SendEtx.setCursorVisible(true);
          }
        } else {
          hideSoftKeyboard();
        }
      }
    });

    mTxt2SendEtx.setOnEditorActionListener(new OnEditorActionListener() {

      @Override
      public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEND) {
          String msg = mTxt2SendEtx.getText().toString().trim();

          if (Tools.isNotEmpty(msg)) {
            if (msg.length() > 100) {
              showToastLong(SpeakForYouActivity.this, "输入不能超过100个字符!");
            } else {
              mTxt2SendEtx.setText("");
              SpeakForYouItem sfyi = new SpeakForYouItem(msg,
                  SpeakForYouType.TEXT, true, PosterType.Parent, DateUtils
                      .getNowDateString(), -1, -1);
              historyWordList.add(sfyi);
              if (sha != null)
                sha.notifyDataSetChanged();
              scrollToBottom();
              speak(msg, sfyi);
            }
          } else {
            mTxt2SendEtx.setText("");
            showToastLong(SpeakForYouActivity.this, "输入字符串为空!");
          }
          handled = true;
        }
        return handled;
      }
    });

    mTxt2SendEtx.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        if (mTxt2SendEtx != null) {
          mTxt2SendEtx.requestFocus();
        }

        if (mTxt2SendEtx != null
            && Tools.isNotEmpty(mTxt2SendEtx.getHint().toString())
            && mTxt2SendEtx.getHint().toString().contains("给宝宝选个故事")) {
          displayRecommend(ResourceType.Text);
          mTxt2SendEtx.setCursorVisible(true);
          foldLayout();
        }

        if (mTxt2SendEtx != null
            && Tools.isNotEmpty(mTxt2SendEtx.getHint().toString())
            && mTxt2SendEtx.getHint().toString().contains("输入文字让小小班")) {
          if (Tools.isEmpty(mTxt2SendEtx.getText().toString().trim())) {
            LeMachine lb = LeXiaoXiaoBanApp.getInstance().getBaby();
            mTxt2SendEtx.setText(lb.name + "，");
            mTxt2SendEtx.setSelection(mTxt2SendEtx.getText().length());
            mTxt2SendEtx.setCursorVisible(true);
          }
        }

        showSoftKeyboard();
      }
    });

    loadLocalBgResource();
  }

  private void loadLocalBgResource() {
    ArrayList<AlbumCollectionItem> list = new ArrayList<AlbumCollectionItem>();

    AlbumCollectionItem aci1 = new AlbumCollectionItem();
    aci1.setName("默认背景");
    aci1.setId(1);
    list.add(aci1);

    aci1 = new AlbumCollectionItem();
    aci1.setName("圣诞礼物");
    aci1.setId(2);
    list.add(aci1);

    aci1 = new AlbumCollectionItem();
    aci1.setName("保护自己");
    aci1.setId(3);
    list.add(aci1);

    aci1 = new AlbumCollectionItem();
    aci1.setName("小小拜年");
    aci1.setId(4);
    list.add(aci1);

    aci1 = new AlbumCollectionItem();
    aci1.setName("穿越星空");
    aci1.setId(5);
    list.add(aci1);

    aci1 = new AlbumCollectionItem();
    aci1.setName("相亲相爱");
    aci1.setId(6);
    list.add(aci1);

    aci1 = new AlbumCollectionItem();
    aci1.setName("现拍背景");
    aci1.setId(7);
    list.add(aci1);

    aci1 = new AlbumCollectionItem();
    aci1.setName("相册选择");
    aci1.setId(8);
    list.add(aci1);

    ChatWallPaperAapter cwpa = new ChatWallPaperAapter(this, list);
    cwpa.setPhotoSourceDelegate(new PhotoSourceDelegate() {

      @Override
      public void onPhotoSource(int source) {
        switch (source) {
        case 1:
          Uri tmpUri1 = getUriToResource(SpeakForYouActivity.this,
              android.R.color.transparent);
          setChatBgWallpaper(Color.parseColor("#f1f1f1"), tmpUri1);
          break;
        case 2:
          Uri tmpUri2 = getUriToResource(SpeakForYouActivity.this,
              R.drawable.christmas_theme);
          setChatBgWallpaper(android.R.color.transparent, tmpUri2);
          break;
        case 3:
          Uri tmpUri3 = getUriToResource(SpeakForYouActivity.this,
              R.drawable.foggy_theme);
          setChatBgWallpaper(android.R.color.transparent, tmpUri3);
          break;

        case 4:
          Uri tmpUri4 = getUriToResource(SpeakForYouActivity.this,
              R.drawable.newspring_theme);
          setChatBgWallpaper(android.R.color.transparent, tmpUri4);
          break;
        case 5:
          Uri tmpUri5 = getUriToResource(SpeakForYouActivity.this,
              R.drawable.through_universe_theme);
          setChatBgWallpaper(android.R.color.transparent, tmpUri5);
          break;
        case 6:
          Uri tmpUri6 = getUriToResource(SpeakForYouActivity.this,
              R.drawable.love_theme);
          setChatBgWallpaper(android.R.color.transparent, tmpUri6);
          break;

        case 7:
          String status = Environment.getExternalStorageState();
          if (status.equals(Environment.MEDIA_MOUNTED)) {
            if (!PHOTO_DIR.exists()) {
              PHOTO_DIR.mkdirs();// 创建照片的存储目录
            }
            fileName = System.currentTimeMillis() + ".jpg";
            mCurrentPhotoFile = new File(PHOTO_DIR, fileName);
            Intent intentC = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            if (Build.VERSION.SDK_INT >= 24) {
              Uri imageUri = FileProvider.getUriForFile(
                  SpeakForYouActivity.this, "com.haoduoai.fileprovider",
                  mCurrentPhotoFile);
              intentC.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
              intentC.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

            } else {
              intentC.putExtra(MediaStore.EXTRA_OUTPUT,
                  Uri.fromFile(mCurrentPhotoFile));
            }
            startActivityForResult(intentC, CAMERA_WITH_DATA);
          } else {
            toastShow("没有SD卡");
          }

          break;
        case 8:
          Intent intent = new Intent();
          intent.addCategory(Intent.CATEGORY_OPENABLE);
          intent.setType("image/*");
          if (Build.VERSION.SDK_INT < 19) {
            intent.setAction(Intent.ACTION_GET_CONTENT);
          } else {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
          }
          startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
          break;
        default:
          DateUtils.showToast(SpeakForYouActivity.this, "全新壁纸，尽情期待!");
          break;
        }
      }
    });

    mBgSelectGv.setAdapter(cwpa);
  }

  private void setChatBgWallpaper(int listViewColor, Uri backgroundUri) {
    mHistoryLV.setBackgroundColor(listViewColor);
    mChangeBgImg.setImageURI(backgroundUri);
    if (backgroundUri != null)
      mChatBgPath = backgroundUri.toString();
    mListViewColor = listViewColor;
  }

  public static final Uri getUriToResource(@NonNull Context context,
      @AnyRes int resId) throws Resources.NotFoundException {
    /** Return a Resources instance for your application's package. */
    Resources res = context.getResources();
    /**
     * Creates a Uri which parses the given encoded URI string.
     *
     * @param uriString
     *          an RFC 2396-compliant, encoded URI
     * @throws NullPointerException
     *           if uriString is null
     * @return Uri for this given uri string
     */
    Uri resUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
        + res.getResourcePackageName(resId) + '/'
        + res.getResourceTypeName(resId) + '/'
        + res.getResourceEntryName(resId));
    /** return uri */
    return resUri;
  }

  /**
   * 调用图片剪辑程序
   */
  @SuppressLint("InlinedApi")
  public Intent getCropImageIntent() {
    Intent intent = new Intent(Intent.ACTION_PICK, null);
    intent.setType("image/*");

    if (Build.VERSION.SDK_INT < 19) {
      setIntentParams(intent);
    } else {
      // TODO
    }

    return intent;
  }

  /**
   * 设置公用参数
   */
  private void setIntentParams(Intent intent) {
    intent.putExtra("crop", "true");
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    intent.putExtra("outputX", 600);
    intent.putExtra("outputY", 600);
    intent.putExtra("noFaceDetection", true); // no face detection
    intent.putExtra("scale", true);
    intent.putExtra("return-data", false);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mResultURI);
    intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
  }

  private void setIntentResult(Uri tmpFile) {
    LeXiaoXiaoBanLog.e(TAG, "set result");
    Intent resultIntent = new Intent();
    resultIntent.putExtra("image", tmpFile.toString());
    setResult(RESULT_OK, resultIntent);

    LePreference.getInstance().save("speak_for_you_listview_bg_color",
        android.R.color.transparent);

    LePreference.getInstance().save("speak_for_you_wallpaper",
        tmpFile.toString());

    setChatBgWallpaper(android.R.color.transparent, tmpFile);
  }

  /**
   * 裁剪图片
   *
   * @param uri
   */
  public void startPhotoZoom(Uri uri) {
    String fileName = System.currentTimeMillis() + ".jpg";
    if (!PHOTO_DIR.exists()) {
      PHOTO_DIR.mkdirs();// 创建照片的存储目录
    }
    mCacheFile = new File(PHOTO_DIR, fileName);
    Uri outputUri = Uri.fromFile(new File(mCacheFile.getPath()));
    String url = FileUtils.getPath(this, uri);

    Intent intent = new Intent("com.android.camera.action.CROP");
    // sdk>=24
    if (Build.VERSION.SDK_INT >= 24) {
      Uri imageUri = FileProvider.getUriForFile(this, "com.haoduoai.fileprovider",
          new File(url));// 通过FileProvider创建一个content类型的Uri
      intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
      intent.putExtra("noFaceDetection", true);// 去除默认的人脸识别，否则和剪裁匡重叠
      intent.setDataAndType(imageUri, "image/*");
      // 19=<sdk<24
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
        && Build.VERSION.SDK_INT < 24) {
      intent.setDataAndType(Uri.fromFile(new File(url)), "image/*");
      // sdk<19
    } else {
      intent.setDataAndType(uri, "image/*");
    }
    intent.putExtra("crop", "true");// crop=true 有这句才能出来最后的裁剪页面.
    intent.putExtra("aspectX", 19);// 这两项为裁剪框的比例.
    intent.putExtra("aspectY", 20);// x:y=1:2
    intent.putExtra("outputX", 600);
    intent.putExtra("outputY", 500);
    intent.putExtra("output", outputUri);
    intent.putExtra("outputFormat", "JPEG");// 返回格式
    startActivityForResult(intent, CROP_PHOTO);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_CANCELED) {
      return;
    }
    switch (requestCode) {
    case PHOTO_PICKED_WITH_DATA:// 相册返回
      Uri uri = data.getData();
      String selectedImagePath = FileUtils.getPath(this, uri);
      mCurrentPhotoFile = new File(selectedImagePath);
      startPhotoZoom(Uri.fromFile(mCurrentPhotoFile));
      break;
    case CAMERA_WITH_DATA:// 相机返回
      if (mCurrentPhotoFile == null || !mCurrentPhotoFile.exists()) {
        mCurrentPhotoFile = new File(PHOTO_DIR, fileName);
      }
      startPhotoZoom(Uri.fromFile(mCurrentPhotoFile));
      break;
    case CROP_PHOTO:// 图片剪裁返回
      if (Tools.isNotEmpty(mCacheFile)) {
        Uri outputUri = Uri.fromFile(mCacheFile);
        Intent resultIntent = new Intent();
        resultIntent.putExtra("image", outputUri.toString());
        setResult(RESULT_OK, resultIntent);

        LePreference.getInstance().save("speak_for_you_listview_bg_color",
            android.R.color.transparent);

        LePreference.getInstance().save("speak_for_you_wallpaper",
            outputUri.toString());

        setChatBgWallpaper(android.R.color.transparent, outputUri);
      }
      break;
    }
  }

  @SuppressLint("SimpleDateFormat")
  @SuppressWarnings("unused")
  private File createImageFile(boolean insideApp) throws IOException {
    // Create an image file name
    if (!insideApp) {
      String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
          .format(new Date());
      String imageFileName = "PNG_" + "tmp" + "_";
      File storageDir = Environment
          .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

      if (!storageDir.exists()) {
        boolean ret = storageDir.mkdir();
        if (!ret) {
          storageDir.mkdirs();
        }
      }

      File image = File.createTempFile(imageFileName, /* prefix */
          ".png", /* suffix */
          storageDir /* directory */
      );

      // Save a file: path for use with ACTION_VIEW intents
      // galleryAddPic(image);// no need to add to the gallery!
      return image;
    } else {
      return new File(mAvatarPath);
    }
  }

  private String[][] getSubArray(String[][] source, int start) {
    String[][] a = new String[1][];
    for (int i = start; i < start + 1 && i < source.length; i++) {
      a[0] = Arrays.copyOfRange(source[i], 0, source[i].length);
    }
    return a;
  }

  private void inflateHistoryData(List<SpeakFouYouRecordItem> sfyris) {
    if (historyWordList != null) {
      int size = sfyris.size();
      int i = 0;
      for (; i != size; i++) {
        SpeakFouYouRecordItem item = sfyris.get(i);
        if (Tools.isEmpty(item.img)) {
          if (Tools.isNotEmpty(item.audio)) {
            SpeakForYouItem sfyi = new SpeakForYouItem(item.audio,
                SpeakForYouType.VOICE, item.success, PosterType.Child,
                item.created_at, item.id, item.episode_id);
            sfyi.hasRead = item.audio_read;
            sfyi.length = item.audio_length;
            sfyi.id = item.id;
            historyWordList.add(0, sfyi);
          } else if (Tools.isNotEmpty(item.poster)
              && item.poster.equals("turing")) {
            historyWordList.add(0, new SpeakForYouItem(item.content,
                SpeakForYouType.TEXT, item.success, PosterType.Turing,
                item.created_at, item.id, item.episode_id));

          } else if (Tools.isNotEmpty(item.content)) {
            historyWordList.add(0, new SpeakForYouItem(item.content,
                SpeakForYouType.TEXT, item.success, PosterType.Parent,
                item.created_at, item.id, item.episode_id));

          }
        } else {
          historyWordList.add(0, new SpeakForYouItem(item.content, item.img,
              item.id, item.episode_id, SpeakForYouType.VIDEO, item.success,
              PosterType.Parent, item.created_at));
        }
      }
      sha = new SpeakWordHistoryAdapter(this, historyWordList);

      mHistoryLV.setAdapter(sha);

      mHistoryLV.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
          // TODO Auto-generated method stub
          foldLayout();
        }
      });

      sha.notifyDataSetChanged();
    }
  }

  private void speak(final String content, final SpeakForYouItem sfyi) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          sfyi.State = SendState.SUCCESS;
        } else {
          sfyi.State = SendState.FAILED;
        }
        uploadRecord(sfyi.id, sfyi.Src, sfyi.Caption, result.isSuccess(), 0,
            sfyi);
        if (sha != null)
          sha.notifyDataSetChanged();
        toastShow(result.data);
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        sfyi.State = SendState.SENDING;
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put("sno", mLeUser.sno);
        param_.put("op", "speech");
        param_.put("content", content);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL + "/api/2.0/device/op",
            param_, HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void scrollMyListViewToBottom() {
    mHistoryLV.post(new Runnable() {
      @Override
      public void run() {
        // Select the last row so it will scroll into view...
        if (sha != null)
          mHistoryLV.setSelection(sha.getCount() - 1);
      }
    });
  }

  private void getHistoryRecords() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @SuppressWarnings("unchecked")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          JSONObject jo;
          try {
            jo = new JSONObject(result.data);
            List<SpeakFouYouRecordItem> sfyris = (List<SpeakFouYouRecordItem>) JsonSerializer
                .getInstance().deserialize(jo.getString("data"),
                    ArrayList.class, SpeakFouYouRecordItem.class);
            if (Tools.isNotEmpty(sfyris) && sfyris.size() != 0) {
              mLastPage++;
              inflateHistoryData(sfyris);
              if (mLastPage == 2)
                scrollMyListViewToBottom();
            }
            mSwipeRefreshLayout.setRefreshing(false);
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put("sno", mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put("page", mLastPage);
        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/member/history/sound", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private boolean needRefresh;

  private void uploadRecord(final int id, final String imgUrl,
      final String content, final boolean success, final int episode_id,
      final SpeakForYouItem sfyi) {
    needRefresh = false;
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (id == -1 && result.isSuccess()) {
          JSONObject jo;
          try {
            jo = new JSONObject(result.data);
            if (jo.has("created_id")) {
              int _id = jo.getInt("created_id");
              sfyi.id = _id;
            }
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }

        if (needRefresh) {
          loadTipWordsByCategory(0, tipWordList.get(0).id, true);
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put("sno", mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        if (Tools.isNotEmpty(imgUrl))
          param_.put("img", imgUrl);
        param_.put("content", content);
        if (episode_id != 0)
          param_.put("episode_id", episode_id);
        if (success) {
          param_.put("success", 1);
        } else {
          param_.put("success", 0);
        }

        int prompt_text_id = -1;
        if (sfyi.SFYType == SpeakForYouType.TEXT
            && sfyi.posterType == PosterType.Parent) {
          if (tipWordListSpArray != null
              && !tipWordListSpArray.get(0).isEmpty()) {
            for (TipWordCategoryItem item : tipWordListSpArray.get(0)) {
              if (content.equalsIgnoreCase(item.name)) {
                prompt_text_id = item.id;
                break;
              }
            }
          }
        }

        if (prompt_text_id != -1) {
          param_.put("prompt_text_id", prompt_text_id);
          needRefresh = true;
        }

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/member/history/sound/" + (id == -1 ? "NA" : id),
            param_, HttpUtils.TAG_PUT_REQUEST);
      }
    }).execute();
  }

  private void hideSoftKeyboard() {
    View view = this.getCurrentFocus();
    if (view != null) {
      InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
      imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
  }

  private void showSoftKeyboard() {

    final View view = this.getCurrentFocus();
    if (view != null) {
      InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
      imm.showSoftInput(view, 0);
    }

  }

  private void expandLayout() {
    RelativeLayout.LayoutParams iParams = (RelativeLayout.LayoutParams) mInputSelectionLayout
        .getLayoutParams();
    iParams.height = Tools.getPixelByDip(this, 264);
    iParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    mInputSelectionLayout.setLayoutParams(iParams);
    RelativeLayout.LayoutParams cParams = (RelativeLayout.LayoutParams) mCenterLayout
        .getLayoutParams();
    cParams.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    mCenterLayout.setLayoutParams(cParams);
  }

  private void foldLayout() {
    RelativeLayout.LayoutParams iParams = (RelativeLayout.LayoutParams) mInputSelectionLayout
        .getLayoutParams();
    iParams.height = 0;
    iParams.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    mInputSelectionLayout.setLayoutParams(iParams);
    RelativeLayout.LayoutParams cParams = (RelativeLayout.LayoutParams) mCenterLayout
        .getLayoutParams();
    cParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
    mCenterLayout.setLayoutParams(cParams);
    mRadioImg.setImageResource(R.drawable.radio_icon);
    mImeImg.setImageResource(R.drawable.ime_icon);
    mChatBgImg.setImageResource(R.drawable.chat_bg_icon);
  }

  private void loadRecommendationData() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @SuppressWarnings("unchecked")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          List<AlbumItem> recommendAlbums = (List<AlbumItem>) JsonSerializer
              .getInstance().deserialize(result.data, ArrayList.class,
                  AlbumItem.class);
          if (Tools.isNotEmpty(recommendAlbums)) {
            setRecommendView(recommendAlbums);
          }
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put("sno", mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/catalog/radio/recommand", param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  private void loadTipWordCategory() {
    new CustomAsyncTask(this, new IAsyncTask() {
      @SuppressWarnings("unchecked")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          tipWordList = (List<TipWordCategoryItem>) JsonSerializer
              .getInstance().deserialize(result.data, ArrayList.class,
                  TipWordCategoryItem.class);
          if (Tools.isNotEmpty(tipWordList) && !tipWordList.isEmpty()) {
            for (int i = 0; i < tipWordList.size(); i++) {
              loadTipWordsByCategory(i, tipWordList.get(i).id, false);
            }
          }
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put("sno", mLeUser.sno);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/operation/sounding_for_you/type", param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  private void loadTipWordsByCategory(final int pos, final int type_id,
      final boolean update) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @SuppressWarnings("unchecked")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        ++tipIndex;
        if (result.isSuccess()) {
          List<TipWordCategoryItem> wlist = (List<TipWordCategoryItem>) JsonSerializer
              .getInstance().deserialize(result.data, ArrayList.class,
                  TipWordCategoryItem.class);

          tipWordListSpArray.put(pos, wlist);
        }

        if (tipIndex >= tipWordList.size() || update) {
          tipIndex = 0;
          initTextCategoryLayout();
          if (update) {
            needRefresh = false;
          }
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put("sno", mLeUser.sno);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/operation/sounding_for_you/type_" + type_id + "/text",
            param_, HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  private void buildCircles() {
    recommend_rbIds = new ArrayList<Integer>();
    int i = 0;
    for (; i < 2; i++) {
      LayoutParams rbParams = new LayoutParams(
          LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
      rbParams.setMargins(Tools.getPixelByDip(this, 10), 0,
          Tools.getPixelByDip(this, 10), 0);
      RadioButton rb = new RadioButton(this);
      rb.setButtonDrawable(R.drawable.gridview_pager_indicator);
      rb.setId(i * 1);
      rb.setPadding(Tools.getPixelByDip(this, 5), 0,
          Tools.getPixelByDip(this, 5), 0);
      rb.setLayoutParams(rbParams);
      recommend_rbIds.add(rb.getId());
      mCircleRg.addView(rb);
    }
  }

  private class RecommendPagerAdapter extends FragmentStatePagerAdapter {
    private List<AlbumItem> mAlbumItemList;
    private OnRecommendItemClickListener mOnRecommendItemClickListener;
    public RecommendPagerAdapter(FragmentManager fm) {
      super(fm);
    }
    public RecommendPagerAdapter(FragmentManager fm, List<AlbumItem> ais,
                                 OnRecommendItemClickListener listener) {
      this(fm);
      mAlbumItemList = ais;
      mOnRecommendItemClickListener = listener;
    }

    @Override
    public int getItemPosition(Object object) {
      return POSITION_NONE;
    }

    @Override
    public Fragment getItem(int pos) {
      pos %= 2;
      int startIndex = pos * 8;
      int endIndex = Math.min((1 + pos) * 8, mAlbumItemList.size());
      return new GridViewFragment(mAlbumItemList.subList(startIndex, endIndex),
          mOnRecommendItemClickListener);
    }

    @Override
    public int getCount() {
      return 2;
    }
  }

  private void setRecommendView(List<AlbumItem> aiList) {
    mRecommendPagerAdapter = new RecommendPagerAdapter(
        getSupportFragmentManager(), aiList,
        new OnRecommendItemClickListener() {

          @Override
          public void onRecommendItemClick(AlbumItem ai) {
            SpeakForYouItem sfyi = new SpeakForYouItem(ai.title,
                ai.album_cover, ai.id, ai.album_id, SpeakForYouType.VIDEO,
                true, PosterType.Parent, DateUtils.getNowDateString());
            historyWordList.add(sfyi);
            if (sha != null)
              sha.notifyDataSetChanged();
            scrollToBottom();
            playvideo(ai.id, "cartoon", sfyi);
          }
        });

    mRecommendVp.setAdapter(mRecommendPagerAdapter);
    mRecommendVp.setOnPageChangeListener(new OnPageChangeListener() {
      @Override
      public void onPageSelected(int arg0) {
        if (arg0 < recommend_rbIds.size()) {
          mCircleRg.check(recommend_rbIds.get(arg0));
        }
      }

      @Override
      public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub
      }

      @Override
      public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub
      }
    });

  }

  private void playvideo(final int sid, final String status,
      final SpeakForYouItem sfyi) {
    new CustomAsyncTask(this, new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          DateUtils.showToast(SpeakForYouActivity.this, "已推送到设备播放");
          sfyi.State = SendState.SUCCESS;

          if (sha != null)
            sha.notifyDataSetChanged();
          uploadRecord(sfyi.id, sfyi.Src, sfyi.Caption, result.isSuccess(),
                  sid, sfyi);
        } else {
          DateUtils.showToast(SpeakForYouActivity.this, "设备不在线");
          sfyi.State = SendState.FAILED;
          LeConfig.isDeviceConnect = false;
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        sfyi.State = SendState.SENDING;
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        int uid = -1, volume = -1, minutes = -1;
        param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_ACTION_I, "play");
        param_.put(HttpUtils.TAG_OPERATION_I, "cartoon");
        param_.put(HttpUtils.TAG_TYPE_I, "cartoon");

        if (sid != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
        }
        param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));
        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  private void scrollToBottom() {
    mHistoryLV.post(new Runnable() {
      @Override
      public void run() {
        if (sha != null)
          mHistoryLV.setSelection(sha.getCount() - 1);
      }
    });
  }

  private int mCurTypeIndex = 0;

  private void highlightSelection(int pos) {
    if (selectedTextViewId != -1) {
      for (TextView tv : categoryTextViewList) {
        if (tv.getId() == selectedTextViewId) {
          tv.setTextColor(Color.argb(255, 43, 172, 252));
        } else {
          tv.setTextColor(oldColors);
        }
      }

      mCurTypeIndex = pos;
      PagerAdapter pa = new TagsPagerAdapter(getSupportFragmentManager(),
          tipWordListSpArray.get(pos));
      mTagsViewPager.setAdapter(pa);
      pa.notifyDataSetChanged();
    }
  }

  private void initTextCategoryLayout() {
    int i = 0;
    int size = tipWordList.size();
    rbIds = new ArrayList<Integer>();
    categoryTextViewList = new ArrayList<TextView>();

    mHLayout.removeAllViews();
    for (; i < size; i++) {
      String cur = tipWordList.get(i).name;
      View hChild = mInflater.inflate(R.layout.text_category_item, null);
      final TextView categoryBtn = (TextView) hChild
          .findViewById(R.id.category_tv);
      categoryBtn.setText(cur);
      categoryBtn.setPadding(Tools.getPixelByDip(this, 20), 0,
          Tools.getPixelByDip(this, 20), 0);
      categoryBtn.setId(11 * i);
      categoryTextViewList.add(categoryBtn);

      if (i == 0) {
        oldColors = categoryBtn.getTextColors(); // save original colors
        selectedTextViewId = categoryBtn.getId();
      }

      categoryBtn.setTag(i);
      categoryBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
          selectedTextViewId = categoryBtn.getId();
          highlightSelection((int) categoryBtn.getTag());
        }
      });

      LayoutParams tvParams = new LayoutParams(
          LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
      hChild.setLayoutParams(tvParams);
      mHLayout.addView(hChild);
    }

    highlightSelection(0);
  }

  private class TagsPagerAdapter extends FragmentStatePagerAdapter {
    private List<TipWordCategoryItem> tags;
    public TagsPagerAdapter(FragmentManager fm) {
      super(fm);
    }
    public TagsPagerAdapter(FragmentManager fm,
        List<TipWordCategoryItem> strArray) {
      this(fm);
      tags = strArray;
    }

    @Override
    public int getItemPosition(Object object) {
      return POSITION_NONE;
    }

    @Override
    public Fragment getItem(int pos) {
      return TagsFragment.newInstance(tags);
    }

    @Override
    public int getCount() {
      // return tags.length;
      return 1;
    }
  }

  /*
   * (non-Javadoc)
   * 
   * @see android.view.View.OnClickListener#onClick(android.view.View)
   */
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.img_closevideo:
      live_video_layout.setVisibility(View.GONE);
      img_closevideo.setVisibility(View.GONE);
      ask_layout.setVisibility(View.VISIBLE);

      final WindowManager.LayoutParams attrs = getWindow().getAttributes();
      attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
      getWindow().setAttributes(attrs);
      getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
      showTitleView();
      break;
    case R.id.radio_img:
      displayRecommend(ResourceType.Video);
      break;
    case R.id.ime_img:
      displayRecommend(ResourceType.Text);
      break;
    case R.id.chat_bg_img:
      displayRecommend(ResourceType.Background);
      break;
    case R.id.ask_search_tv:
      Intent intent = new Intent(this, WebViewContainerActivity.class);
      intent.putExtra("h5url",
          "http://www.xiaoxiaoban.com.cn/search/search.html");
      startActivity(intent);
      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
      break;
    default:
      break;
    }
  }

  private void displayRecommend(ResourceType rt) {
    hideSoftKeyboard();
    mTxt2SendEtx.setText("");
    mTxt2SendEtx.setCursorVisible(false);

    switch (rt) {
    case Video:
      mTagsViewPager.setVisibility(View.GONE);
      bottomHS.setVisibility(View.GONE);
      mBgSelectGv.setVisibility(View.GONE);
      mRecommendVp.setVisibility(View.VISIBLE);
      mCircleRg.setVisibility(View.VISIBLE);
      mViewPagerIndicators.setVisibility(View.GONE);
      mTxt2SendEtx.setHint(getResources().getString(
          R.string.quick_story_input_prompt));
      mRadioImg.setImageResource(R.drawable.radio_icon_highlight);
      mImeImg.setImageResource(R.drawable.ime_icon);
      mChatBgImg.setImageResource(R.drawable.chat_bg_icon);
      break;
    case Text:
      mTagsViewPager.setVisibility(View.VISIBLE);
      bottomHS.setVisibility(View.VISIBLE);
      mRecommendVp.setVisibility(View.GONE);
      mCircleRg.setVisibility(View.GONE);
      mBgSelectGv.setVisibility(View.GONE);
      mViewPagerIndicators.setVisibility(View.VISIBLE);
      mTxt2SendEtx.setHint(getResources().getString(
          R.string.quick_text_input_prompt));
      mRadioImg.setImageResource(R.drawable.radio_icon);
      mImeImg.setImageResource(R.drawable.ime_icon_highlight);
      mChatBgImg.setImageResource(R.drawable.chat_bg_icon);

      mTxt2SendEtx.setTag(false);
      if (Tools.isEmpty(mTxt2SendEtx.getText().toString().trim())) {
        LeMachine lb = LeXiaoXiaoBanApp.getInstance().getBaby();
        mTxt2SendEtx.setText(lb.name + "，");
        mTxt2SendEtx.setSelection(mTxt2SendEtx.getText().length());
        mTxt2SendEtx.requestFocus();
        mTxt2SendEtx.setCursorVisible(true);
      }

      break;
    case Background:
      mBgSelectGv.setVisibility(View.VISIBLE);
      mTagsViewPager.setVisibility(View.GONE);
      bottomHS.setVisibility(View.GONE);
      mRecommendVp.setVisibility(View.GONE);
      mCircleRg.setVisibility(View.GONE);
      mRadioImg.setImageResource(R.drawable.radio_icon);
      mImeImg.setImageResource(R.drawable.ime_icon);
      mChatBgImg.setImageResource(R.drawable.chat_bg_icon_highlight);
      break;
    default:
      break;
    }
    expandLayout();
  }

  private void checkUserImSig() {
    SocketThreadManager.getInstance().setDataReceivedListener(this);
    SocketThreadManager.getInstance().setDeviceStateListener(this);
  }

  @Override
  public void onDataReceived(String data) {
    if (Tools.isNotEmpty(data)) {
      try {
        JSONObject jsonData = new JSONObject(data.toString());
        if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("act")) {
          SpeakForYouItem sfyi = null;
          String actStr = jsonData.getString("act");
          if (actStr.contains("audio")) {
            String realData = jsonData.getString("data");
            if (Tools.isNotEmpty(realData)) {
              JSONObject jo = new JSONObject(realData);
              int id = jo.getInt("id");
              String src = jo.getString("src");
              String length = jo.getString("length");
              sfyi = new SpeakForYouItem(src, SpeakForYouType.VOICE, true,
                  PosterType.Child, DateUtils.getNowDateString(), id, -1);
              sfyi.id = id;
              sfyi.length = length;
              sfyi.hasRead = false;
            }
          } else if (actStr.contains("turing")) {
            String realData = jsonData.getString("data");
            sfyi = new SpeakForYouItem(realData, SpeakForYouType.TEXT, true,
                PosterType.Turing, DateUtils.getNowDateString(), -1, -1);
          } else if (actStr.contains("Device_Login")) {
            LeConfig.isDeviceConnect = true;
          } else if (actStr.contains("Device_Logout")) {
            LeConfig.isDeviceConnect = false;
          } else if (actStr.contains("Device_APP_Connection_Switched")) {
            // Intent logoutIntent = new Intent(
            // "com.jdy.haoduoai.activity.logout");
            // sendBroadcast(logoutIntent);
            //
            // LeConfig.isLogin = false;
            // LeConfig.isDeviceActivated = false;
            // LeConfig.isDeviceBinded = false;
            // LeConfig.isInfoFilled = false;
            // LeConfig.isDeviceConnect = false;
            //
            // CustomOneBtnDialog.Builder cdb = new CustomOneBtnDialog.Builder(
            // getApplicationContext()).setTitle("下线通知")
            // .setMessage("您有其他亲友正在连接控制小小班设备，请休息片刻。")
            // .setPositiveButton("确定", new DialogInterface.OnClickListener() {
            //
            // @Override
            // public void onClick(DialogInterface dialog, int which) {
            // dialog.dismiss();
            // }
            // });
            // final CustomOneBtnDialog cd = cdb.create();
            // cd.getWindow()
            // .setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            // cd.setOnDismissListener(new OnDismissListener() {
            //
            // @Override
            // public void onDismiss(DialogInterface dialog) {
            // Intent toActivityIntent = new Intent(SpeakForYouActivity.this,
            // LoginActivity.class);
            // toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
            // | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // startActivity(toActivityIntent);
            // finish();
            // }
            // });
            // cd.show();
          }
          if (sfyi != null) {
            historyWordList.add(sfyi);

            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                if (sha != null)
                  sha.notifyDataSetChanged();
                scrollToBottom();
              }
            });
          }
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }

  @Override
  public void onRefresh() {
    mSwipeRefreshLayout.setRefreshing(true);
    getHistoryRecords();
  }

  @Override
  public void onRemoteLogin() {
    runOnUiThread(new Runnable() {

      @Override
      public void run() {
        if (device_view != null) {
          device_view.setPlaying(false);
        }
      }
    });

  }

  @Override
  public void onConnectionChanged(final boolean connect) {

  }

  @Override
  public void onPowerChanged(int power) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onUpgrade(int updatingStatus) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onCheckDeviceVersion(String version) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayNextFailed() {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayPrevFailed() {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayMedia(final PlayState playState, MediaType type,
                          JSONObject data) {

    runOnUiThread(new Runnable() {

      @Override
      public void run() {
        // TODO Auto-generated method stub
        if (device_view != null) {
          if (playState.equals(PlayState.Playing)) {
            device_view.setPlaying(true);
          } else {
            device_view.setPlaying(false);
          }
        }
      }
    });

  }

  @Override
  public void onReceivedVoiceMessage(String streamUrl) {
    // TODO Auto-generated method stub

  }
}
